﻿using Mapster;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Senparc.Weixin.Work.AdvancedAPIs.OaDataOpen;
using SHZY.BaseData.Entitys.Common.Dto.Factory;
using SHZY.BaseData.Entitys.Common.Dto.Modeling;
using SHZY.BaseData.Entitys.Common.Dto.Station;
using SHZY.BaseData.Entitys.Common.Entity;
using SHZY.BaseData.Interfaces.Common;
using SHZY.ClayObject;
using SHZY.Common.Configuration;
using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Manager.Files;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Filter;
using SHZY.Common.Helper;
using SHZY.Common.Models.NPOI;
using SHZY.Common.Security;
using SHZY.DataEncryption;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Entitys.System;
using SHZY.Systems.Interfaces.System;
using SqlSugar;

namespace SHZY.BaseData.Common;

/// <summary>
/// 业务实现：工序信息.
/// </summary>
[ApiDescriptionSettings(Tag = "BaseData", Name = "Modeling", Order = 200)]
[Route("api/Common/BaseData/[controller]")]
public class ComBaseModelingService : IComBaseModelingService, IDynamicApiController, ITransient
{
    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<ComBaseFactorystructureEntity> _factory;

    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<ComBaseModelingEntity> _repository;

    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<ComBaseStationEntity> _repositorys;

    /// <summary>
    /// 服务基础仓储.
    /// </summary>
    private readonly ISqlSugarRepository<ComBaseArtroutedetailEntity> _repositorydetail;

    /// <summary>
    /// 多租户事务.
    /// </summary>
    private readonly ITenant _db;

    /// <summary>
    /// 数据接口服务.
    /// </summary>
    private readonly IDataInterfaceService _dataInterfaceService;

    /// <summary>
    /// 用户管理.
    /// </summary>
    private readonly IUserManager _userManager;

    /// <summary>
    /// 初始化一个<see cref="ComBaseModelingService"/>类型的新实例.
    /// </summary>
    ///
    /// <summary>
    /// 文件管理.
    /// </summary>
    private readonly IFileManager _fileManager;

    public ComBaseModelingService(
        ISqlSugarRepository<ComBaseModelingEntity> qmsBaseModelingRepository,
        ISqlSugarRepository<ComBaseStationEntity> qmsBaseStationRepository,
        ISqlSugarRepository<ComBaseArtroutedetailEntity> qmsBaseArtroutedetailEntity,
        ISqlSugarRepository<ComBaseFactorystructureEntity> qmsBaseFactorystructureRepository,
        IDataInterfaceService dataInterfaceService,
        ISqlSugarClient context,
        IFileManager fileManager,
        IUserManager userManager)
    {
        _factory = qmsBaseFactorystructureRepository;
        _repository = qmsBaseModelingRepository;
        _repositorys = qmsBaseStationRepository;
        _repositorydetail = qmsBaseArtroutedetailEntity;
        _dataInterfaceService = dataInterfaceService;
        _fileManager = fileManager;
        _db = context.AsTenant();
        _userManager = userManager;
    }

    /// <summary>
    /// 获取工序信息.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<dynamic> GetInfo(string id)
    {
        //return (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<ComBaseModelingInfoOutput>();
        var data = (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<ComBaseModelingInfoOutput>();
        return data;
    }

    /// <summary>
    /// 获取工序信息列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("")]
    public async Task<dynamic> GetList([FromQuery] ComBaseModelingListQueryInput input)
    {
        var queryable = _repository.Context.Queryable<ComBaseModelingEntity>()
            .LeftJoin<ComBaseStationEntity>((a, b) => a.StationCode == b.EnCode && a.WorkshopId == b.ParentId)
            .WhereIF(!string.IsNullOrEmpty(input.enCode), (a, b) => a.EnCode.Contains(input.enCode))
            .WhereIF(!string.IsNullOrEmpty(input.fullName), (a, b) => a.FullName.Contains(input.fullName))
            .WhereIF(!string.IsNullOrEmpty(input.desc), (a, b) => a.Desc.Contains(input.desc))
            .WhereIF(!string.IsNullOrEmpty(input.stationCode), (a, b) => a.StationCode.Equals(input.stationCode))
            .Where((a, b) => a.DeleteMark == null)
            .WhereIF(!string.IsNullOrEmpty(input.keyword), (a, b) => a.EnCode.Contains(input.keyword) || a.FullName.Contains(input.keyword) || a.Desc.Contains(input.keyword) || a.StationCode.Contains(input.keyword))
            .Select((a, b) => new ComBaseModelingListOutput
            {
                id = a.Id,
                enCode = a.EnCode,
                fullName = a.FullName,
                stationCode = b.FullName,
                workshopId = a.WorkshopId,
                workshopCode = a.WorkshopCode,
                workshopName = a.WorkshopName,
                desc = a.Desc,
                enabledMark = SqlFunc.IIF(a.EnabledMark == 0, "禁用", "正常"),
            }).MergeTable();
        if (!string.IsNullOrEmpty(input.sidx))
        {
            queryable.OrderBy(input.sidx + " " + input.sort);
        }
        else
        {
            queryable.OrderByDescending(it => it.enCode);
        }
        var data = await queryable.ToPagedListAsync(input.currentPage, input.pageSize);
        return PageResult<ComBaseModelingListOutput>.SqlSugarPageResult(data);
    }

    /// <summary>
    /// 新建工序信息.
    /// </summary>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPost("")]
    public async Task CreateModeling([FromBody] ComBaseModelingCrInput input)
    {
        if (await _repository.AnyAsync(x => x.EnCode == input.enCode && x.DeleteMark == null))
            throw Oops.Oh(ErrorCode.COM1004);
        var entity = input.Adapt<ComBaseModelingEntity>();
        entity.CreatorTime = DateTime.Now;
        entity.Id = SnowflakeIdHelper.NextId();

        if (!string.IsNullOrEmpty(entity.WorkshopCode))
        {
            var FactoryData = await _factory.AsQueryable().Where(x => x.EnCode == entity.WorkshopCode && x.Type == "Workshop" && x.DeleteMark == null).FirstAsync();
            entity.WorkshopId = FactoryData.Id;
            entity.WorkshopName = FactoryData.FullName;
        }

        var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
        if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);
    }

    /// <summary>
    /// 获取工序信息无分页列表.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    public async Task<dynamic> GetNoPagingList([FromQuery] ComBaseModelingListQueryInput input)
    {
        return await _repository.Context.Queryable<ComBaseModelingEntity>()
            .LeftJoin<ComBaseStationEntity>((a, b) => a.StationCode == b.EnCode && a.WorkshopId == b.ParentId)
            .WhereIF(!string.IsNullOrEmpty(input.enCode), (a, b) => a.EnCode.Contains(input.enCode))
            .WhereIF(!string.IsNullOrEmpty(input.fullName), (a, b) => a.FullName.Contains(input.fullName))
            .WhereIF(!string.IsNullOrEmpty(input.desc), (a, b) => a.Desc.Contains(input.desc))
            .WhereIF(!string.IsNullOrEmpty(input.stationCode), (a, b) => a.StationCode.Equals(input.stationCode))
            .WhereIF(!string.IsNullOrEmpty(input.keyword), (a, b) => a.EnCode.Contains(input.keyword) || a.FullName.Contains(input.keyword) || a.Desc.Contains(input.keyword) || a.StationCode.Contains(input.keyword))
            .Where((a, b) => a.DeleteMark == null)
            .OrderByIF(string.IsNullOrEmpty(input.sidx), (a, b) => a.Id)
            .Select((a, b) => new ComBaseModelingListOutput
            {
                id = a.Id,
                enCode = a.EnCode,
                fullName = a.FullName,
                stationCode = b.FullName,
                workshopId = a.WorkshopId,
                workshopCode = a.WorkshopCode,
                workshopName = a.WorkshopName,
                desc = a.Desc,
                enabledMark = SqlFunc.IIF(a.EnabledMark == 0, "禁用", "正常"),
            }).OrderByIF(!string.IsNullOrEmpty(input.sidx), a => input.sidx + " " + input.sort).ToListAsync();
    }

    /// <summary>
    /// 导出工序信息.
    /// </summary>
    /// <param name="input">请求参数.</param>
    /// <returns></returns>
    [HttpGet("Actions/Export")]
    public async Task<dynamic> Export([FromQuery] ComBaseModelingListQueryInput input)
    {
        var exportData = new List<ComBaseModelingListOutput>();
        if (input.dataType == 0)
            exportData = Clay.Object(await GetList(input)).Solidify<PageResult<ComBaseModelingListOutput>>().list;
        else
            exportData = await GetNoPagingList(input);
        List<ParamsModel> paramList = "[{\"value\":\"工序名称\",\"field\":\"fullName\"},{\"value\":\"工序编码\",\"field\":\"enCode\"},{\"value\":\"说明描述\",\"field\":\"desc\"},{\"value\":\"默认工位\",\"field\":\"stationCode\"},{\"value\":\"车间编码\",\"field\":\"workshopCode\"},{\"value\":\"车间名称\",\"field\":\"workshopName\"},{\"value\":\"有效标志\",\"field\":\"enabledMark\"},]".ToList<ParamsModel>();
        ExcelConfig excelconfig = new ExcelConfig();
        excelconfig.FileName = "工序信息.xls";
        excelconfig.HeadFont = "微软雅黑";
        excelconfig.HeadPoint = 10;
        excelconfig.IsAllSizeColumn = true;
        excelconfig.ColumnModel = new List<ExcelColumnModel>();
        foreach (var item in input.selectKey.Split(',').ToList())
        {
            var isExist = paramList.Find(p => p.field == item);
            if (isExist != null)
                excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value });
        }

        var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
        ExcelExportHelper<ComBaseModelingListOutput>.Export(exportData, excelconfig, addPath);
        var fileName = _userManager.UserId + "|" + addPath + "|xls";
        return new
        {
            name = excelconfig.FileName,
            url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "SHZY")
        };
    }

    /// <summary>
    /// 批量删除工序信息.
    /// </summary>
    /// <param name="ids">主键数组.</param>
    /// <returns></returns>
    [HttpPost("batchRemove")]
    public async Task delupdateModelingBatch([FromBody] List<string> ids)
    {
        var entitys = await _repository.Context.Queryable<ComBaseModelingEntity>().In(it => it.Id, ids).ToListAsync();
        if (entitys.Count > 0)
        {
            try
            {
                // 开启事务
                _db.BeginTran();

                // 批量删除工序信息
                var isOk = await _repository.Context.Updateable<ComBaseModelingEntity>().SetColumns(it => new ComBaseModelingEntity()
                {
                    DeleteTime = DateTime.Now,
                    DeleteMark = 1,
                    DeleteUserId = _userManager.UserId
                }).Where(it => ids.Contains(it.Id)).ExecuteCommandHasChangeAsync();

                // 关闭事务
                _db.CommitTran();
            }
            catch (Exception)
            {
                // 回滚事务
                _db.RollbackTran();

                throw Oops.Oh(ErrorCode.COM1002);
            }
        }
    }

    /// <summary>
    /// 更新工序信息.
    /// </summary>
    /// <param name="id">主键值.</param>
    /// <param name="input">参数.</param>
    /// <returns></returns>
    [HttpPut("{id}")]
    public async Task updateModeling(string id, [FromBody] ComBaseModelingUpInput input)
    {
        try
        {
            // 开启事务
            _db.BeginTran();

            if (await _repository.AnyAsync(x => x.EnCode == input.enCode && x.DeleteMark == null && x.Id != input.id))
                throw Oops.Oh(ErrorCode.COM1004);

            var data = await _repository.Context.Queryable<ComBaseModelingEntity>().Where(x => x.Id == input.id).ToListAsync();

            var entity = input.Adapt<ComBaseModelingEntity>();
            entity.LastModifyTime = DateTime.Now;
            entity.WorkshopId = "";
            entity.WorkshopName = "";
            if (!string.IsNullOrEmpty(entity.WorkshopCode))
            {
                var FactoryData = await _factory.AsQueryable().Where(x => x.EnCode == entity.WorkshopCode && x.Type == "Workshop" && x.DeleteMark == null).FirstAsync();
                entity.WorkshopId = FactoryData.Id;
                entity.WorkshopName = FactoryData.FullName;
            }

            var query = await _repositorydetail.Context.Queryable<ComBaseArtroutedetailEntity>().Where(x => x.EnCode == data.First().EnCode).ToListAsync();
            if (query.Count > 0)
            {
                foreach (var item in query)
                {
                    item.EnCode = entity.EnCode;
                    item.FullName = entity.FullName;
                    item.StationCode = entity.StationCode;
                }

                var flg = await _repositorydetail.Context.Updateable(query).UpdateColumns(it => new
                {
                    it.EnCode,
                    it.FullName,
                    it.StationCode
                }).ExecuteCommandAsync();

                if (!(flg > 0)) throw Oops.Oh(ErrorCode.COM1001);
            }

            var isOk = await _repository.Context.Updateable(entity).UpdateColumns(it => new
            {
                it.EnCode,
                it.FullName,
                it.Desc,
                it.StationCode,
                it.WorkshopName,
                it.WorkshopCode,
                it.WorkshopId,
                it.EnabledMark,
                it.LastModifyTime,
            }).ExecuteCommandAsync();

            if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1001);
            // 关闭事务
            _db.CommitTran();
        }
        catch (Exception ex)
        {
            // 回滚事务
            _db.RollbackTran();
            //throw Oops.Oh(ErrorCode.COM1001);
            throw Oops.Oh(ex.Message);
        }
    }

    /// <summary>
    /// 删除工序信息.
    /// </summary>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public async Task deleteModeling(string id)
    {
        var isOk = await _repository.Context.Updateable<ComBaseModelingEntity>().SetColumns(it => new ComBaseModelingEntity()
        {
            DeleteTime = DateTime.Now,
            DeleteMark = 1,
            DeleteUserId = _userManager.UserId
        }).Where(it => it.Id.Equals(id)).ExecuteCommandHasChangeAsync();
        if (!isOk)
            throw Oops.Oh(ErrorCode.COM1002);
    }

    /// <summary>
    /// 上传文件.
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [HttpPost("Uploader")]
    public async Task<dynamic> Uploader(IFormFile file)
    {
        try
        {
            var _filePath = _fileManager.GetPathByType(string.Empty);
            var _fileName = DateTime.Now.ToString("yyyyMMdd") + "_" + SnowflakeIdHelper.NextId() + Path.GetExtension(file.FileName);
            var stream = file.OpenReadStream();
            await _fileManager.UploadFileByType(stream, _filePath, _fileName);
            return new { name = _fileName, url = string.Format("/api/File/Image/{0}/{1}", string.Empty, _fileName) };
        }
        catch (Exception)
        {
            throw Oops.Oh(ErrorCode.D8001);
        }
    }

    /// <summary>
    /// 导入数据.
    /// </summary>
    /// <param name="input">请求参数</param>
    /// <returns></returns>
    [HttpPost("ImportData")]
    public async Task<dynamic> ImportData([FromBody] ComBaseModelingImportDataInput input)
    {
        var output = new ComBaseModelingImportDataOutput();
        foreach (var item in input.list)
        {
            try
            {
                if (await _repository.AnyAsync(x => x.FullName == item.fullName && x.DeleteMark == null))
                    throw Oops.Oh(ErrorCode.COM1004);

                var StationList = await _repositorys.AsQueryable().Where(x => x.DeleteMark == null).ToListAsync();
                var FactoryList = await _factory.AsQueryable().Where(x => x.DeleteMark == null).ToListAsync();

                var entity = item.Adapt<ComBaseModelingEntity>();

                //验证参数信息
                if (string.IsNullOrEmpty(entity.FullName))
                {
                    item.exceptionMsg = "请输入工序名称！";
                    output.failResult.Add(item);
                    output.fnum++;
                    continue;
                }
                if (string.IsNullOrEmpty(entity.EnCode))
                {
                    item.exceptionMsg = "请输入工序编码！";
                    output.failResult.Add(item);
                    output.fnum++;
                    continue;
                }
                if (!string.IsNullOrEmpty(entity.Desc))
                {
                    if (entity.Desc.Trim().Length > 500)
                    {
                        item.exceptionMsg = "说明长度不能超过500字！";
                        output.failResult.Add(item);
                        output.fnum++;
                        continue;
                    }
                }
                if (!string.IsNullOrEmpty(entity.StationCode))
                {
                    var Station = StationList.Find(x => x.FullName == item.stationCode);
                    if (Station == null)
                    {
                        item.exceptionMsg += "默认工位不存在!";
                        output.failResult.Add(item);
                        output.fnum++;
                        continue;
                    }
                    else
                    {
                        entity.StationCode = Station.EnCode;
                    }
                }
                if (!string.IsNullOrEmpty(entity.WorkshopCode))
                {
                    var Factory = FactoryList.Find(x => x.EnCode == item.workshopCode && x.Type == "Workshop" && x.DeleteMark == null && x.EnabledMark == 1);
                    if (Factory == null)
                    {
                        item.exceptionMsg += "车间不存在!";
                        output.failResult.Add(item);
                        output.fnum++;
                        continue;
                    }
                    else
                    {
                        //根据车间判断工位
                        var stationparentId = StationList.Find(x => x.FullName == item.stationCode).ParentId;
                        if (Factory.Id != stationparentId)
                        {
                            item.exceptionMsg += "该车间不存在此工位!";
                            output.failResult.Add(item);
                            output.fnum++;
                            continue;
                        }
                        entity.WorkshopId = Factory.Id;
                        entity.WorkshopCode = Factory.EnCode;
                        entity.WorkshopName = Factory.FullName;
                    }
                }
                entity.EnabledMark = 1;
                var isOK = await _repository.Context.Insertable(entity).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                if (isOK < 1)
                {
                    output.failResult.Add(item);
                    output.fnum++;
                }
                else
                {
                    output.snum++;
                }
            }
            catch (Exception ex)
            {
                item.exceptionMsg = ex.Message;
                output.failResult.Add(item);
                output.fnum++;
            }
        }
        if (output.snum == input.list.Count)
        {
            output.resultType = 1;
        }
        else
        {
            output.resultType = 0;
        }
        return output;
    }

    /// <summary>
    /// 模板下载.
    /// </summary>
    /// <returns></returns>
    [HttpGet("TemplateDownload")]
    public async Task<dynamic> TemplateDownload()
    {
        string _fileName = "工序信息.xlsx";
        var filePath = Path.Combine(FileVariable.TemplateFilePath, "modeling_import_template.xlsx"); // 模板路径
        var addFilePath = Path.Combine(FileVariable.TemplateFilePath, _fileName); // 保存路径
        if (!await _fileManager.ExistsFile(addFilePath))
        {
            var stream = await _fileManager.GetFileStream(filePath);
            await _fileManager.UploadFileByType(stream, FileVariable.TemporaryFilePath, _fileName);
        }

        return new { name = _fileName, url = "/api/file/Download?encryption=" + DESCEncryption.Encrypt(_userManager.UserId + "|" + _fileName, "SHZY") };
    }

    /// <summary>
    /// 导入预览.
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    [HttpGet("ImportPreview")]
    public async Task<dynamic> ImportPreview(string fileName)
    {
        try
        {
            var filePath = FileVariable.TemporaryFilePath;
            var savePath = Path.Combine(filePath, fileName);
            // 得到数据
            var sr = await _fileManager.GetFileStream(savePath);
            var excelData = ExcelImportHelper.ToDataTable(savePath, sr);
            foreach (var item in excelData.Columns)
            {
                excelData.Columns[item.ToString()].ColumnName = GetFileEncode(item.ToString());
            }
            // 删除文件
            await _fileManager.DeleteFile(savePath);
            // 返回结果
            return new { dataRow = excelData };
        }
        catch (Exception)
        {
            throw Oops.Oh(ErrorCode.D1801);
        }
    }

    #region PrivateMethod

    private string GetFileEncode(string filed)
    {
        switch (filed)
        {
            case "工序名称":
                return "fullName";

            case "工序编码":
                return "enCode";

            case "默认工位":
                return "stationCode";

            case "说明描述":
                return "desc";

            case "车间名称":
                return "workshopName";

            case "车间编码":
                return "workshopCode";

            case "车间id":
                return "workshopId";

            default:
                return string.Empty;
        }
    }

    #endregion PrivateMethod

    /// <summary>
    /// 获取工位信息.
    /// </summary>
    /// <returns></returns>
    [HttpGet("All")]
    public async Task<dynamic> getStationList()
    {
        var data = await _repositorys.AsQueryable().Where(x => x.DeleteMark == null && x.EnabledMark == 1).OrderBy(x => x.EnCode).ToListAsync();
        return new { list = data.Adapt<List<ComBaseStationInfoOutput>>() };
    }

    /// <summary>
    /// 获取对应工位信息.
    /// </summary>
    /// <returns></returns>
    [HttpGet("AllStationList/{workshopCode}")]
    public async Task<dynamic> getWorkStationList(string workshopCode)
    {
        var factoryInfo = await _factory.AsQueryable().Where(a => a.EnCode == workshopCode && a.Type == "Workshop" && a.DeleteMark == null && a.EnabledMark == 1).FirstAsync();

        if (factoryInfo != null)
        {
            var code = factoryInfo.Id;
            var data = await _repositorys.AsQueryable().Where(x => x.ParentId == code && x.DeleteMark == null && x.EnabledMark == 1).OrderBy(x => x.EnCode).ToListAsync();
            return new { list = data.Adapt<List<ComBaseStationInfoOutput>>() };
        }
        return new { list = new List<ComBaseStationInfoOutput>() };
    }

    /// <summary>
    /// 获取工序信息.
    /// </summary>
    /// <returns></returns>
    [HttpGet("ModelingAll")]
    public async Task<dynamic> getModelingList()
    {
        var data = await _repository.AsQueryable().Where(x => x.DeleteMark == null && x.EnabledMark == 1).OrderBy(x => x.EnCode).ToListAsync();
        return new { list = data.Adapt<List<ComBaseModelingListOutput>>() };
    }
}